<template>
    <div class='productForm'>
        <div class="tabHeader">
            <el-tabs v-model="editableTabsValue" @tab-click="handleTabClick">
                <el-tab-pane v-for="(item,index) in editableTabs" :key="item.id" :name="item.name" :label="item.name">
                    <!-- <span slot="label">
                        <el-popover placement="bottom-start"
                            popper-class='custom'>
                            <span slot="reference">{{item.name}}</span>
                        </el-popover>
                    </span> -->
                </el-tab-pane>
            </el-tabs>
            <div class="setBtn">
                <el-button type="primary" plain size='mini' class="el-icon-circle-check"
                    @click="$refs.saveScheme.showDialog()">
                    保存当前</el-button>
                <el-button type="primary" size='mini' class="el-icon-edit-outline" @click="$refs.scheme.drawerOpen()">
                    筛选方案
                </el-button>
            </div>
        </div>
        <dynamic-form :formDataList="formDataList" @getFormData='getFormData' ref='dynamicForm'></dynamic-form>
        <custom-setbtn>
            <template #l_btn>
                <div class="l_btn">
                    <el-button
                        type="primary"
                        size="mini"
                        icon="el-icon-upload2"
                        plain
                        @click='getProduceReportExport'
                        :disabled="tableList.length <= 0"
                    >
                        导出
                    </el-button>
                </div>
            </template>
            <template #r_btn>
                <div class="r_btn">
                    <!-- 列配置表格 -->
                    <pop-checkbox :disposeGroup='disposeGroup' @handleChangeDiposeGroup='handleChangeDiposeGroup'></pop-checkbox>
                </div>
            </template>
        </custom-setbtn>
        <tableList
            :tableGroup='tableGroup'
            :tableList='tableList'
            @getTableData='getTableData'
            :searchForm='searchForm'
            ref='tableList'>
        </tableList>

        <!-- 保存当前 -->
        <save-current ref="saveScheme" @getList='getList' :editableTabs='editableTabs' @fromOutDrawerClose='fromOutDrawerClose'></save-current>

        <!-- 筛选方案--创建方案 -->
        <operate-scheme ref="scheme" :editableTabs='editableTabs1' @getList='getList' @fromOutDrawerClose='fromOutDrawerClose'
            @lastData='lastData'></operate-scheme>
    </div>
</template>

<script>
import dynamicForm from '@/components/dynamicForm'
import tableList from '../components/tableList.vue'
import saveCurrent from './saveCurrent.vue'
import operateScheme from './operateScheme.vue'
import { productColumns } from '@/api/customFieldController'
import {
    produceReport,
} from '@/api/statisticsController'
 import {
    screenPlanList
} from '@/api/produceController'
export default {
    components: {
        dynamicForm,
        tableList,
        saveCurrent,
        operateScheme
    },
    data() {
        return {
            editableTabsValue: '',
            editableTabs: [],
            editableTabs1: [],
            // 表单列表
            formDataList: {
                formGroup: [
                    {
                        label: 'workOrderCode',
                        name: '工单编号',
                        prop: '',
                        placeholder: '请输入',
                        key: 'srk'
                    },
                    {
                        label: 'workOrderState',
                        name: '工单状态',
                        prop: '',
                        placeholder: '请选择',
                        key: 'sel',
                        node: {
                            isRadio: false,
                            default: '',
                            options: [
                                { value: '0', label: '未开始' },
                                { value: '1', label: '执行中' },
                                { value: '2', label: '已结束' },
                                { value: '3', label: '已取消' }
                            ]
                        }
                    },
                    {
                        label: ['workOrderEndTimeStart', 'workOrderEndTimeEnd'],
                        name: '工单实际结束时间',
                        prop: '',
                        key: 'cki'
                    },
                    {
                        label: ['reportStartTimeStart', 'reportStartTimeEnd'],
                        name: '报工开始时间',
                        prop: '',
                        key: 'cki'
                    },
                    {
                        label: ['reportEndTimeStart', 'reportEndTimeEnd'],
                        name: '报工结束时间',
                        prop: '',
                        placeholder: '请输入产品编号',
                        key: 'cki'
                    },
                    {
                        label: ['actualStartTime', 'actualEndTime'],
                        name: '实际报工时间',
                        prop: '',
                        key: 'cki',
                        defaultTime: true,
                        defaultValue: ''
                    },
                    {
                        label: 'productName',
                        name: '产品名称',
                        prop: '',
                        placeholder: '请输入产品名称',
                        key: 'srk'
                    },
                    {
                        label: 'produceUser',
                        name: '生产人员',
                        prop: '',
                        placeholder: '请选择',
                        key: 'sci',
                        dataUrl: {
                            url: '/user/user_list_o',
                            value: 'id'
                        } 
                    },
                    {
                        label: 'depIds',
                        name: '部门',
                        prop: '',
                        placeholder: '请选择',
                        key: 'sci',
                        dataUrl: {
                            url: '/base/dep_other',
                            value: 'id'
                        }
                    },
                    {
                        label: 'processIds',
                        name: '工序',
                        prop: '',
                        placeholder: '请选择',
                        key: 'sci',
                        dataUrl: {
                            url: '/base/process_other',
                            value: 'code',
                            chat:'-'
                        }
                    },
                    {
                        label: 'specification',
                        name: '产品规格',
                        prop: '',
                        placeholder: '请输入产品规格',
                        key: 'srk'
                    },
                    {
                        label: ['workOrderStartTimeStart', 'workOrderStartTimeEnd'],
                        name: '工单计划开始时间',
                        prop: '',
                        key: 'cki',
                        defaultTime: true,
                        defaultValue: ''
                    },
                    {
                        label: ['workOrderEndTimeStart', 'workOrderEndTimeEnd'],
                        name: '工单计划结束时间',
                        prop: '',
                        key: 'cki',
                        defaultTime: true,
                        defaultValue: ''
                    },
                    {
                        label: ['workOrderActualStartTimeStart', 'workOrderActualStartTimeEnd'],
                        name: '工单实际开始时间',
                        prop: '',
                        key: 'cki',
                        defaultTime: true,
                        defaultValue: ''
                    },
                    {
                        label: 'comment',
                        name: '工单备注',
                        prop: '',
                        placeholder: '请输入备注',
                        key: 'srk'
                    },
                    {
                        label: 'missionState',
                        name: '任务状态',
                        prop: '',
                        placeholder: '请选择',
                        key: 'sel',
                        node: {
                            isRadio: false,
                            default: '',
                            options: [
                                { value: '0', label: '未开始' },
                                { value: '1', label: '执行中' },
                                { value: '2', label: '已结束' }
                            ]
                        }
                    },
                    {
                        label: ['missionStartTimeStart', 'missionStartTimeEnd'],
                        name: '任务计划开始时间',
                        prop: '',
                        key: 'cki',
                        defaultTime: true,
                        defaultValue: ''
                    },
                    {
                        label: ['missionEndTimeStart', 'missionEndTimeEnd'],
                        name: '任务计划结束时间',
                        prop: '',
                        key: 'cki',
                        defaultTime: true,
                        defaultValue: ''
                    },
                    {
                        label: ['missionActualStartTimeStart', 'missionActualStartTimeEnd'],
                        name: '任务实际开始时间',
                        prop: '',
                        key: 'cki',
                        defaultTime: true,
                        defaultValue: ''
                    },
                    {
                        label: ['missionActualEndTimeStart', 'missionActualEndTimeEnd'],
                        name: '任务实际结束时间',
                        prop: '',
                        key: 'cki',
                        defaultTime: true,
                        defaultValue: ''
                    },
                    {
                        label: ['verifyTimeStart', 'verifyTimeEnd'],
                        name: '审批时间',
                        prop: '',
                        key: 'cki',
                        defaultTime: true,
                        defaultValue: ''
                    },
                    
                    {
                        label: 'badProductId',
                        name: '不良品原因',
                        prop: '',
                        placeholder: '请选择',
                        key: 'sci',
                        dataUrl: {
                            url: '/base/bp_other',
                            value: 'id',
                            chat: '|'
                        }
                    },
                    {
                        label: 'pricing',
                        name: '计价方式',
                        prop: '',
                        placeholder: '请选择',
                        key: 'sel',
                        node: {
                            isRadio: true,
                            default: '',
                            options: [
                                { value: '0', label: '计件' },
                                { value: '1', label: '计时' }
                            ]
                        }
                    },
                    {
                        label: 'verifyState',
                        name: '审批状态',
                        prop: '',
                        placeholder: '请选择',
                        key: 'sel',
                        node: {
                            isRadio: true,
                            default: '',
                            options: [
                                { value: '0', label: '未审批' },
                                { value: '1', label: '已审批' }
                            ]
                        }
                    },
                    {
                        label: 'verifyUser',
                        name: '审批人',
                        prop: '',
                        placeholder: '请选择',
                        key: 'sci',
                        dataUrl: {
                            url: '/user/user_list_o',
                            value: 'id'
                        } 
                    },
                ],
                searchForm: {
                    workOrderCode: '',
                    workOrderState: [],
                    workOrderActualEndTimeStart: '',
                    workOrderActualEndTimeEnd: '',
                    reportStartTimeStart: '',
                    reportStartTimeEnd: '',
                    reportEndTimeStart: '',
                    reportEndTimeEnd: '',
                    actualStartTime: '',
                    actualEndTime: '',
                    productName: '',
                    produceUser: '',
                    depIds: '',
                    processIds: ''
                },
                formSet: true,
                type: 'productForm',

            },
            searchForm:{
                customFieldMap:{},
                searchOther:{},
                page:1,
                limit:10,
            },
            disposeGroup: [],
            tableGroup: [],
            // 表格数据
            tableList: [],
            fromSavaCurrent: 0,
            isMounted:'',
            enumState:{
                0:'未开始',
                1:'执行中',
                2:'已结束',
                3:'已取消'
            },
            enumDynamicType:{
                1:'今天',
                2:'昨天',
                3:'本周',
                4:'上周',
                5:'本月',
                6:'上月',
                7:'近三月',
            },
            customFieldMap:{},
            defaultTabs: [
                {
                    id: -11,
                    name: "今日员工报工",
                    screenCondition: "{\"configData\":[]}",
                    type: 3
                },
                {
                    id: -12,
                    name: "本月员工报工",
                    screenCondition: "{\"configData\":[]}",
                    type: 3
                },
                {
                    id: -13,
                    name: "全部员工报工",
                    screenCondition: "{\"configData\":[]}",
                    type: 3
                },
            ],
            allTabs:[],
            secondGroupInfo:[],
        }
    },
    created() {
        this.defaultTabs.map(item => {
            item.screenCondition = this.tabsDefaultTime(item.name)
        })
    },
    mounted() {
        let tabs = this.$route.query.tabs
        if(tabs) {
            let obj = {
                name: "全部员工报工",
                screenCondition: "{\"configData\":[]}"
            }
            this.schemeClick(obj)
        } else {
            this.isMounted = 'mounted'
        }
        this.getProductColumns({type: 'productForm'})
            .then(()=>{
                if(this.editableTabsValue == 1) {
                    let date = new Date(), y = date.getFullYear(), m = date.getMonth() + 1, d = date.getDate();
                    m < 10 ? m = '0' + m : ''
                    d < 10 ? d = '0' + d : ''
                    data.actualEndTime = y + '-' + m + '-' + d + ' 23:59:59'
                    data.actualStartTime = y + '-' + m + '-' + d + ' 00:00:00'
                }
            })
        this.getScreenPlanList({type:3})
    },
    methods: {
        getProductColumns: async function(data){
            const res = await productColumns(data)
            if (res.code == 200) {
                this.disposeGroup = []
                this.tableGroup = []
                res.data.map((item, i) => {
                    const key = {
                        index:'80',
                        workOrderCode:'160',
                        productCode:'160',
                        productName:'130',
                        productSpecification:'70',
                        clientName:'70',
                        planedNumber:'90',
                        workOrderState:'80',
                        workOrderStartTime:'145',
                        workOrderEndTime:'145',
                        workOrderActualStartTime:'145',
                        workOrderActualEndTime:'145',
                        processOrder:'80',
                        processName:'130',
                        rate:'90',
                        processStartTime:'145',
                        processEndTime:'145',
                        processActualStartTime:'145',
                        processActualEndTime:'145',
                        processPlanedNumber:'90',
                        processActualNumber:'90'
                    }
                    let width = key[item.name] ?? '180'
                    if (item.state) {
                        this.tableGroup.push({
                            label: item.name,
                            name: item.chineseName,
                            width
                        })
                    }
                    this.disposeGroup.push({
                        label: item.name,
                        name: item.chineseName,
                        state: item.state
                    })
                })
            }
        },
        //监视复选框值变化
        handleChangeDiposeGroup(disposeGroup) {
            let configureList = []
            configureList = disposeGroup.map(i => {
                return {
                    name: i.label,
                    chineseName: i.name,
                    state: i.state
                }
            })
            this.getProductColumns({
                type: 'productForm',
                configureList
            }).then(()=>{
                this.$refs.tableList.changeLayout() //防止改变table列配置出现抖动
            })
        },
        // 表格数据
        getTableData(data) {
            this.$refs.tableList.onloadLogin(true)
            produceReport(data).then(res => {
                if(res.code == 200) {
                    this.tableList = res.data.records
                    this.tableList.map((item, i) => {
                        item.index = (res.data.current - 1) * 10 + (i + 1)
                        if(item.customFieldVos != null) {
                            item.customFieldVos.map(k => {
                                item[k.customFieldId] = k.value,
                                item.customType = k.customFieldMess.fieldType
                            })
                        }
                    })
                    this.$refs.tableList.totalNum(res.data.total)
                }
                this.$refs.tableList.onloadLogin(false)
            })
        },
        tabsDefaultTime(name) {
            let date = new Date()
            let year = date.getFullYear()
            let month = date.getMonth() + 1
            let day = date.getDate()
            let dateObj = new Date(year,month,0); 
            let theMonthDay = dateObj.getDate();
            let startTime = ''
            let endTime = ''
            let obj = {
                configData: [
                    {
                        chineseName: name,
                        fieldId: "actualTime",
                        compType: '1',
                        fieldValue: []
                    }
                ]
            }
            month < 10 ? month = '0' + month : ''
            day < 10 ? day = '0' + day : ''
            if(name == '今日员工报工') {
                startTime = year + '-' + month + '-' + day + ' 00:00:00'
                endTime = year + '-' + month + '-' + day + ' 23:59:59'
                obj.configData[0].fieldValue = [startTime, endTime]
            } else if(name == '本月员工报工') {
                startTime = year + '-' + month + '-' + '01 00:00:00'
                endTime = year + '-' + month + '-' + theMonthDay + ' 23:59:59'
                obj.configData[0].fieldValue = [startTime, endTime]
            } else if(name == '全部员工报工') {
                obj.configData[0].fieldValue = []
            }
            return JSON.stringify(obj)
        },
        //点击查询获取表单数据
        getFormData(val){
            this.formDataList.searchForm = val
            this.handleFormData(val)
            this.getTableData(this.searchForm)
        },
        // 导出
        getProduceReportExport() {
            this.$refs.tableList.getTableData('生产报表' + new Date().dateFormat('yyyyMMddhhmmss'), '/statistics/produce_report', this.searchForm)
        },

        // 筛选方案--保存当前============================
        //获取筛选方案列表
        getList(payload){
            this.fromSavaCurrent = payload == undefined || payload.length
            this.getScreenPlanList({type:3},payload == undefined || {delIndex:payload.delIndex,name:payload.name})
        },
        //筛选方案列表
        getScreenPlanList(data, p) {
            screenPlanList(data,p).then(res => {
                if (res.code == 200) {
                    this.tabsList = []
                    this.editableTabs = [...this.defaultTabs, ...res.data]
                    this.editableTabs.forEach(i => {
                        this.tabsList = [...this.tabsList,JSON.parse(i.screenCondition).configData]
                    })
                    this.editableTabs1 = res.data

                    /**
                     * 当选中第n个tabs标签页，此时打开筛选方案删除当前第n条数据时，tabs下划线默认向前移动一位
                     */
                    if(p != undefined && p.delIndex != undefined && p.name == this.editableTabsValue) {
                        let ind = p.delIndex + 2
                        this.editableTabsValue = this.editableTabs[ind].name
                    }
                    /**
                     * 保存当前 || 筛选方案-创建筛选方案方式创建第一条筛选方案时调用列表接口
                     * isMounted : 筛选方案-创建筛选方案方式创建第一条筛选方案时调用列表接口
                     *             当创建第二条以上时将isMounted = '' 不需要再调用列表接口
                     */
                    if(this.isMounted == 'mounted' || this.fromSavaCurrent === 1) this.schemeClick(this.editableTabs[0])

                }
            })
        },
        //tabs标签页--popover框
        schemeClick(item){
            this.searchForm = { //多个筛选方案互相切换先置空
                customFieldMap:{},
                searchOther:{},
                page:1,
                limit:10,
            }
            this.isMounted = ''
            /**
             * getValue 这个方法单独获取已填写的非筛选方案表单项的数据
             * 若通过selectData获取会触发'getFormData'导致每次点击筛选方案tabs标签重复调用列表接口
             */
            let formDataPayload = this.$refs.dynamicForm.getValue()
            this.handleSchemeData(item)
            this.handleFormData(formDataPayload)
            this.getTableData(this.searchForm)
        },
        //处理筛选方案表单项自定义和非自定义字段数据
        handleSchemeData(item){
            let screenCondition = []
            let payload = {}
            screenCondition = JSON.parse(item.screenCondition).configData
            screenCondition.forEach(i => {
                if(i.fieldId == 'depIds' || i.fieldId == 'badProduct' || i.fieldId == 'processIds' || i.fieldId == 'produceUser' || i.fieldId == 'verifyUser'){
                    let str = []
                    i.fieldValue.map(item => {
                        str.push(item.value)
                    })
                    payload[i.fieldId] = str
                }else if(i.fieldId.indexOf('Time') != -1){
                    if(i.fieldId == 'actualTime') {
                        payload['actualStartTime'] = i.fieldValue[0]
                        payload['actualEndTime'] = i.fieldValue[1]
                    } else {
                        payload[i.fieldId + 'Start'] = i.fieldValue[0]
                        payload[i.fieldId + 'End'] = i.fieldValue[1]
                    }
                }else if(i.type != undefined && i.type != 'selectRadio' && i.type != 'ipt'){
                    let str = ''
                    i.fieldValue.forEach(k =>{
                        str += k + ','
                    })
                    if(str.length > 0) str = str.substr(0,str.length - 1)
                    payload[i.fieldId] = str
                }else{
                    payload[i.fieldId] = i.fieldValue
                }
            })
            this.editableTabsValue = item.name
            for (const key in payload) {
                if (!isNaN(parseFloat(key)) && isFinite(key)) {
                    this.searchForm.customFieldMap[key] = payload[key]
                }else{
                    this.searchForm[key] = payload[key]
                }
            }
        },
        //处理非筛选方案表单项自定义和非自定义字段数据
        handleFormData(val){
            this.searchForm.searchOther = {}
            this.customFieldMap = {}
            for (const key in val) {
                /**
                 * 自定义字段表单数据放在searchOther中的customFieldMap对象中
                 * 其中计数器--日期选择器--多选框以 `[自定义字段id]:'arr[0],arr[1]'` 形式传给后端
                 * 其它类型表单项以`[自定义字段id]:'value' 形式传给后端
                 */
                if (!isNaN(parseFloat(key)) && isFinite(key)) { 
                    let str = ''
                    if(Array.isArray(val[key])){
                        val[key].forEach(k => str += k + ',')
                        if(str.length > 0) str = str.substr(0,str.length - 1)
                    }
                    this.customFieldMap[key] = Array.isArray(val[key]) ? str : val[key]
                    this.searchForm.searchOther.customFieldMap = this.customFieldMap
                }else{ //非自定义字段表单数据放在searchOther对象中
                    this.searchForm.searchOther[key] = val[key]
                }
            }
            //点击查询按钮时需要将筛选方案表单项数据和非筛选方案表单项数据同时接收，做合并查询
            if(this.editableTabs.length){ 
                const findTab = this.editableTabs.find(i => i.name == this.editableTabsValue)
                this.handleSchemeData(findTab)
            }
        },
        handleTabClick(tab){
            const target = this.editableTabs.find(i => i.name == tab.label)
            this.schemeClick(target)
        },
        //关闭筛选方案列表
        fromOutDrawerClose(){
            if(this.editableTabs.length){ //当没有筛选方案时不需要调用列表接口
                const findTab = this.editableTabs.find(i => i.name == this.editableTabsValue)
                this.schemeClick(findTab)
            }
        },
        //删除筛选方案最后一条数据时
        lastData(){
            // let payload = {
            //     searchOther:{
            //         state:[-1]
            //     },
            //     page:1,
            //     limit:10,
            // }
            // this.getTableData(payload)
        },
    },
}
</script>

<style lang="less" scoped>
.productForm {
    overflow: auto;
    // /deep/ .searchContent {
    //     border: none
    // }
    .tabHeader {
        height: 44px;
        background-color: rgb(250, 250, 250);
        padding-left: 10px;

        .el-tabs {
            float: left;
            max-width: 1000px;
        }

        /deep/ .el-tabs__header {
            margin: 0;
            padding-top: 4px;
        }

        /deep/ .el-tabs__nav-wrap::after {
            opacity: 0;
        }

        /deep/ .el-tabs__item {
            padding: 0 10px;
        }

        /deep/ .el-tabs__item:first-child {
            padding-left: 0px;
        }
        /deep/ .el-tabs__item:last-child {
            padding-right: 0px;
        }


        /deep/ .el-tabs__nav {
            height: 40px;
        }

        /deep/ .el-tabs__nav-next, /deep/ .el-tabs__nav-prev{
            line-height: 38px;
        }

        .setBtn {
            float: right;
            margin-top: 8px;
            margin-right: 20px;
        }
    }
}
</style>